package com.fwtai.tool;

import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.CompressionLevel;
import net.lingala.zip4j.model.enums.CompressionMethod;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

/**
 * 文件处理
 */
public final class ToolFile{

  /**
   * 删除文件及文件夹,若本身是文件夹最后已被删除
   * @param fileOrPath 若是文件则删除文件;若是文件夹则删除里面的文件最后删除本身文件夹
   * @作者 田应平
   * @QQ 444141300
   * @创建时间 2024/2/22 18:41
  */
  public static boolean delete(final String fileOrPath) throws IOException{
    final Path path= Paths.get(fileOrPath);
    Files.walkFileTree(path,new SimpleFileVisitor<Path>(){
      //遍历删除文件
      public FileVisitResult visitFile(final Path file,final BasicFileAttributes attrs) throws IOException {
        Files.delete(file);
        return FileVisitResult.CONTINUE;
      }
      //遍历删除目录
      public FileVisitResult postVisitDirectory(final Path dir,final IOException exc) throws IOException{
        Files.delete(dir);
        return FileVisitResult.CONTINUE;
      }
    });
    return true;
  }

  /*
   * 文件转字节流
   * */
  public byte[] getBytes(File file){
    byte[] fileBuff = null;
    try{
      fileBuff = FileUtils.readFileToByteArray(file);
    }catch(IOException e){
      e.printStackTrace();
    }
    return fileBuff;
  }

  /**
   * 字节流转字符流
   * @return
   */
  public char[] getChars(byte[] bytes){
    Charset cs = Charset.forName("UTF-8");
    ByteBuffer bb = ByteBuffer.allocate(bytes.length);
    bb.put(bytes).flip();
    CharBuffer cb = cs.decode(bb);
    return cb.array();
  }

  /**
   * 压缩|打包成.zip文件,压缩包含当前目录及目录下的文件夹,出异常则压缩失败
   * @param folderPath 需要压缩的目标目录;如 D:\\zip\\dir
   * @param zipFilePath 压缩成功后zip文件,含全路径;如 D:\\zip\\dir\\zipxx.zip
  */
  public static void zipCompressFolder(final String folderPath,final String zipFilePath) throws Exception{
    final ZipFile zipFile = new ZipFile(zipFilePath);
    final ZipParameters parameters = new ZipParameters();
    parameters.setCompressionMethod(CompressionMethod.DEFLATE);
    parameters.setCompressionLevel(CompressionLevel.MAXIMUM);
    zipFile.addFolder(new File(folderPath),parameters);
  }
}